# -*- coding: utf-8 -*-

"""
统计英文文章中单词个数，并在图形界面中显示结果，支持界面自定义排序。
"""

import string
import sys
import re

from PyQt4 import QtCore
from PyQt4 import QtGui
from PyQt4.QtGui import QApplication

class Statistic():
    """
    统计类，记录统计信息。
    """
    def __init__(self):
        
        self.table = {}
        self.dict = {}

    def start(self, data):
        """开始统计"""
        strs = re.split(ur'[\s,.;()!?]', data)
        strip = string.whitespace + string.punctuation + string.digits + "\"'"
        
        for word in strs:
            word = word.strip(strip)
            if len(word) > 1:
                if word in self.dict:
                    self.dict[word] += 1
                else:
                    self.dict[word] = 1

        # 返回按键值排序列表(由于TableWidget已经开启了排序，其实这个排序已经没用了)
        self.table = sorted(self.dict.items(), key=lambda t:t[1], reverse = True)

    def show_table_widget(self, parent):
        """显示统计结果组件"""
        tb = TableWidget(parent, self.table)
        tb.show()
        tb.exec_()

class TableWidget(QtGui.QDialog):
    """
    用于显示统计结果的组件
    """
    def __init__(self, parent, dict):
        """
        初始化统计组件的信息，设置窗体大小
        """
        QtGui.QDialog.__init__(self, parent)
        self.setWindowTitle(QApplication.translate("MainWindow", 'Statistic'))
        self.setMinimumSize(236, 500)
        self.setMaximumSize(236, 500)
        
        self.wordCount = len(dict)
        self.table = QtGui.QTableWidget(self.wordCount, 2)
        self.table.setHorizontalHeaderLabels([
                                              QApplication.translate("Statistic", 'Word'),
                                              QApplication.translate("Statistic", 'Count')
                                              ])
        
        self.hori = QtGui.QHBoxLayout(self)
        self.hori.setMargin(0)
        self.hori.addChildWidget(self.table)
        
        rowCount = 0
        for word in dict:
            self.table.setItem(rowCount, 0, QtGui.QTableWidgetItem(word[0]))
            item = QtGui.QTableWidgetItem()
            # 设置为数值类型
            item.setData(0, word[1])
            self.table.setItem(rowCount, 1, item)
            rowCount += 1
        
        self.table.setSortingEnabled(True)
        
        # 默认以第二列，降序排序
        self.table.sortByColumn(1, 1)


if __name__ == "__main__": 
    app = QtGui.QApplication(sys.argv)
    data = "Hello World! my god! you cangddd!    Hello World \n qhm \n qhm"
    statistic = Statistic()
    statistic.start(data)
    statistic.show_table_widget(None)
    app.exec_()

